package me.acomma.groot.interfaces.controller;

import lombok.extern.slf4j.Slf4j;
import me.acomma.groot.application.role.RoleApplicationService;
import me.acomma.groot.application.role.RoleData;
import me.acomma.groot.application.user.*;
import me.acomma.groot.infrastructure.Pagination;
import me.acomma.groot.infrastructure.RestResult;
import me.acomma.groot.application.user.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {
    @Autowired
    private UserApplicationService userApplicationService;

    @Autowired
    private RoleApplicationService roleApplicationService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @GetMapping("/page")
    public RestResult page(PageQueryUserCommand command) {
        Pagination<UserData> pagination = userApplicationService.pageQuery(command);
        return RestResult.success(pagination);
    }

    @GetMapping("/detail")
    public RestResult detail(@RequestParam("userId") Long userId) {
        UserData u = userApplicationService.get(userId);
        return RestResult.success(u);
    }

    @PostMapping("/create")
    public RestResult create(@RequestBody CreateUserCommand command) {
        userApplicationService.create(command);
        return RestResult.success();
    }

    @PostMapping("/modify")
    public RestResult modify(@RequestBody ModifyUserCommand command) {
        userApplicationService.modify(command);
        return RestResult.success();
    }

    @PostMapping("/remove")
    public RestResult remove(@RequestParam("userId") Long userId) {
        userApplicationService.remove(userId);
        return RestResult.success();
    }

    @GetMapping("/role")
    public RestResult assignedRole(@RequestParam("userId") Long userId) {
        List<RoleData> roles = roleApplicationService.getRoleByUserId(userId);
        return RestResult.success(roles);
    }

    @PostMapping("/role")
    public RestResult assignRole(@RequestBody AssignRoleCommand command) {
        userApplicationService.assignRole(command);
        return RestResult.success();
    }
}
